// 处理动态路由

import router from "./index";

/**
 * 处理动态路由
 * @param routes 未处理路由data
 */
export const dealWithRoute = (routes) => {
    let modules = import.meta.glob("/src/**/**.vue");
    // 清空main下的children
    router.options.routes[2].children = []
    let childrenArray = [];
    routes.forEach(route => {
        const e = {
            meta: {}
        }
        const {id, pid, child, component, icon, name, path} = route
        if (path === '') {
            return;
        }
        if (component === 'Layout') {
            return;
        } else {
            // e['component'] = getComponent(component)
            e['component'] = modules[`/src/${component}.vue`]
        }
        if (name != null) {
            e['name'] = path.slice(1)
        }
        e['meta']['title'] = name
        e['path'] = `${path}`
        childrenArray.push(e)
        router.addRoute('main', e)
    })
    router.addRoute({
        path: '/:catchAll(.*)',
        redirect: '/404'
    })
    // 为main添加children子路由
    router.options.routes[2].children.concat(...childrenArray)
}

/**
 * 动态加载组件
 * @param component 组件名称
 * @returns {function(): Promise<*>}
 */
function getComponent(component) {
    return () => import( /* @vite-ignore */ `/src/${component}.vue`)
}
